<template>
  <div class="fee-pane">
    <!-- 订单信息 -->
    <ve-card title="订单信息">
      <ve-cell label="预计租赁周期">
        <view class="order-time-range">
          <view>{{ `${form.expectedUseCarTime} - ${form.expectedReturnCarTime}` }}</view>
          <view class="rent-summary">租期：{{ form.leaseNumberStr || '-' }}</view>
        </view>
      </ve-cell>
      <ve-cell label="车牌号">{{ form.licenseNo || '-' }}</ve-cell>
      <ve-cell label="车型">{{ form.originalModelName || '-' }}</ve-cell>
      <ve-cell label="订单获取方式">{{ form.orderAcquisitionTypeName || '-' }}</ve-cell>
    </ve-card>
    <!-- 费用相关信息 -->
    <ve-form :model="feeForm" ref="feeFormRef" layout="vertical" :rules="rules">
      <fee-pane
        :isReletOrder="true"
        :orderFeeIndex="0"
        :feeTypeSwitch="false"
        @viewPriceCalendar="viewPriceCalendarFn"
        @feeChange="feeChangeFn"
      />
    </ve-form>
    <!-- 收款方式 -->
    <order-payment-pane v-if="feeRealtimeSum > 0" :contractAmount="feeRealtimeSum" />
  </div>
</template>

<script setup name="ShortOrderForm">
  import { ref, inject, computed } from 'vue'
  import {
    getStoreTemplateDetail,
    initFeeDetail,
    buildCostInfoParam,
    getOrderFeeRules,
    handleAddserviceDefaultFee,
  } from '../../components/order-fee/fee-utils.js'
  import feePane from '../../components/order-fee/fee-pane.vue'
  import orderPaymentPane from '../../components/order-payment-pane.vue'
  import { getFeeSum } from '../../components/order-fee/fee-statistic'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'

  const form = inject('form')
  const feeForm = inject('feeForm')
  const feeFormRef = ref({})

  // 实时费用信息开始
  const feeRealtimeSum = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      return getFeeSum(orderFee)
    }
    return 0
  })

  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '月租价（标准）') {
      let target = option.find((item) => item.itemName == '车辆租金')
      if (target) target.amount = val * calcRate.value
    }
    if (itemName == '手续费（标准）') {
      let target = option.find((item) => item.itemName == '手续费')
      if (target) target.amount = val * 1
    }
    if (itemName == '基础保险（标准）') {
      let target = option.find((item) => item.itemName == '基础保险')
      if (target) target.amount = val * calcRate.value
    }
  }

  // 读取门店模板配置，初始化 feeForm
  // form 聚焦部分字段是否发生变化
  const isChangeFormByProps = (propStrList, prevForm) => {
    let formVal = form.value
    return propStrList.some((prop) => formVal[prop] != prevForm[prop])
  }

  const storeTemplate = ref({})
  const initFeeForm = (callback) => {
    getStoreTemplateDetail(form.value.siteId, 2, (template, templateId) => {
      storeTemplate.value = template
      let feeValue = feeForm.value
      initFeeDetail(feeValue, template)
      // 更新费用模板 id
      feeForm.value.orderFee[0].priceTemplateId = templateId

      callback && callback()
    })
  }

  // 表单规则
  const rules = computed(() => {
    return getOrderFeeRules(feeForm.value.orderFee)
  })

  const initStoreTemplate = (prevForm, defaultFee) => {
    return new Promise((resolve) => {
      if (isChangeFormByProps(['siteId'], prevForm)) {
        initFeeForm(() => {
          // 初始化费用
          if (defaultFee) {
            handleDefaultFee(defaultFee, storeTemplate.value)
          }
          resolve()
        })
      } else {
        // 初始化费用
        if (defaultFee) {
          handleDefaultFee(defaultFee, storeTemplate.value)
        }
        resolve()
      }
    })
  }
  const calcRate = ref()
  // 获取默认费用
  // 车型价格模板 id
  const priceModelId = ref()
  const handleDefaultFee = (defaultFee = {}, storeTemplate) => {
    const { basePrice, otherPrice, rate } = defaultFee
    calcRate.value = rate
    priceModelId.value = basePrice.id
    let feeValue = feeForm.value
    let feeDetailList = feeValue.orderFee[0].feeDetailList
    // 处理增值服务费默认值
    handleAddserviceDefaultFee(feeDetailList, storeTemplate, rate)
    if (otherPrice.length > 0) {
      feeDetailList.forEach((feeCategory) => {
        // 基础费项 增值服务费 押金费用
        if (['basicFee', 'addServiceFee', 'depositFee'].includes(feeCategory.type)) {
          let childrenList = feeCategory?.childrenList
          if (childrenList) {
            for (let i = 0; i < childrenList.length; i++) {
              let feeItem = childrenList[i]
              let feeName = feeItem.itemName
              let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
              if (findIndex >= 0) {
                let fee = otherPrice[findIndex]
                feeItem.statics = true
                if (fee?.amount >= 0) {
                  feeItem.amount = fee.amount
                } else {
                  feeItem.amount = undefined
                }
              }
            }
          }
        }
      })
    }
    if (basePrice) {
      feeDetailList.forEach((feeCategory) => {
        const { type, childrenList } = feeCategory
        if (type == 'basicFee') {
          // 日租价 车辆租金 手续费 基础保险
          childrenList.forEach((feeItem) => {
            const { itemName } = feeItem
            if (itemName == '月租价（标准）') {
              if (basePrice?.price >= 0) {
                feeItem.amount = basePrice.price
              }
            }
            if (itemName == '手续费（标准）') {
              if (basePrice?.poundageAmount >= 0) {
                feeItem.amount = basePrice.poundageAmount
              }
            }
            if (itemName == '基础保险（标准）') {
              if (basePrice?.insuranceAmount >= 0) {
                feeItem.amount = basePrice.insuranceAmount
              }
            }
            if (itemName == '手续费') {
              if (basePrice?.poundageAmount >= 0) {
                feeItem.amount = basePrice.poundageAmount
              }
            }
          })
        }
        if (type == 'depositFee') {
          // 日租价 车辆租金 手续费 基础保险
          childrenList.forEach((feeItem) => {
            const { itemName } = feeItem
            if (itemName == '租车押金') {
              if (basePrice?.carDeposit >= 0) feeItem.amount = basePrice?.carDeposit
            }
            if (itemName == '违章押金') {
              if (basePrice?.illegalDeposit >= 0) feeItem.amount = basePrice?.illegalDeposit
            }
          })
        }
      })
    }
  }
  const { foldValidate } = useFormFold([])
  const getCostInfo = (callback) => {
    // 验证费用是否必填
    feeFormRef.value.validate((valid, errors) => {
      if (valid) {
        let costInfo = buildCostInfoParam(feeForm.value)
        callback(costInfo)
      } else {
        // 页面滚动到错误位置
        foldValidate(errors, true)
      }
    })
  }

  // 查看价格日历
  const viewPriceCalendarFn = () => {
    let start = dayjs(form.value.expectedUseCarTime).startOf('month').format('YYYY-MM-DD HH:mm:ss')
    uni.navigateTo({
      url: `/pages/order/price-calendar?priceModelName=${form.value.originalModelName}&priceModelId=${priceModelId.value}&start=${start}`,
    })
  }

  defineExpose({
    getCostInfo,
    initStoreTemplate,
  })
</script>

<style lang="less" scoped>
  .order-time-range {
    font-size: 30rpx;
    font-weight: 400;
    color: #191c27;
    line-height: 44rpx;
    .rent-summary {
      color: #3072f6ff;
      margin-top: 8rpx;
    }
  }

  .form-block {
    background: #f7f8fa;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    box-sizing: border-box;
    padding: 0 24rpx;
  }
</style>
